<?php
/**
 * Created by JetBrains PhpStorm.
 * User: brianjeppesen
 * Date: 7/30/11
 * Time: 2:14 PM
 * To change this template use File | Settings | File Templates.
 */


//Enter you IDs
define("Access_Key_ID", "AKIAJVJTIWZXTELKIJGQ");
define("Secret_Access_Key", "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");
//define("Associate_tag", "");
//define("Signature", "XFYn9K2QO4kdFJA%2BG06e8JgKVaNthdlCKD%2B8YOKsUow%3D");
//define("Timestamp", "2011-07-31T00%3A41%3A54.000Z");

//xml?AWSAccessKeyId=AKIAJVJTIWZXTELKIJGQ&Timestamp=2011-07-31T00%3A41%3A54.000Z&Signature=XFYn9K2QO4kdFJA%2BG06e8JgKVaNthdlCKD%2B8YOKsUow%3D

function ItemLookup($asin) {
    //Define the request
//$request = "http://ecs.amazonaws.com/onca/xml?Service=AWSECommerceService&AWSAccessKeyId=".Access_Key_ID."&AssociateTag=".Associate_tag."&Signature=".Signature."&Timestamp=".Timestamp."&Version=2009-03-31&Operation=ItemLookup&ItemId=$asin&ResponseGroup=Medium,Offers";

    //$request = "http://ecs.amazonaws.com/onca/xml?AWSAccessKeyId=AKIAJVJTIWZXTELKIJGQ&Keywords=harry%20potter&Operation=ItemSearch&SearchIndex=Books&Service=AWSECommerceService&Timestamp=2011-07-31T00%3A54%3A25.000Z&Version=2009-03-31&Signature=Bj1Snowi5S3ePnmChop3OsUZumzm62xcAkL3fHGnocc%3D";


    /*$canonicalQuery = "http://ecs.amazonaws.com/onca/xml?AWSAccessKeyId=" . Access_Key_ID .
                   "&Keywords=harry%20potter" .
                   "&Operation=ItemSearch" .
                   "&SearchIndex=Books" .
                   "&Service=AWSECommerceService" .
                   "&Version=2009-03-31";*/

    $canonicalQuery = "http://ecs.amazonaws.com/onca/xml?AWSAccessKeyId=" . Access_Key_ID .
                   "&ItemId=" . $asin .
                   "&Operation=ItemLookup" .
                   "&ResponseGroup=Images,ItemAttributes" .
                   "&Service=AWSECommerceService" .
                   "&Version=2009-03-31";

    $url = signAmazonUrl($canonicalQuery, Secret_Access_Key);

$session = curl_init($url);
	curl_setopt($session, CURLOPT_HEADER, false);
	curl_setopt($session, CURLOPT_RETURNTRANSFER, true);
	$response = curl_exec($session);
	curl_close($session);
	//$response = file_get_contents($request);
	//$parsed_xml = simplexml_load_string($response);

	header("Content-Type:text/xml");
    echo $response;
}

function signAmazonUrl($url, $secret_key)
{
    $original_url = $url;

    // Decode anything already encoded
    $url = urldecode($url);

    // Parse the URL into $urlparts
    $urlparts       = parse_url($url);

    // Build $params with each name/value pair
    foreach (split('&', $urlparts['query']) as $part) {
        if (strpos($part, '=')) {
            list($name, $value) = split('=', $part, 2);
        } else {
            $name = $part;
            $value = '';
        }
        $params[$name] = $value;
    }

    // Include a timestamp if none was provided
    if (empty($params['Timestamp'])) {
        $params['Timestamp'] = gmdate('Y-m-d\TH:i:s\Z');
    }

    // Sort the array by key
    ksort($params);

    // Build the canonical query string
    $canonical       = '';
    foreach ($params as $key => $val) {
        $canonical  .= "$key=".rawurlencode(utf8_encode($val))."&";
    }
    // Remove the trailing ampersand
    $canonical       = preg_replace("/&$/", '', $canonical);

    // Some common replacements and ones that Amazon specifically mentions
    $canonical       = str_replace(array(' ', '+', ',', ';'), array('%20', '%20', urlencode(','), urlencode(':')), $canonical);

    // Build the sign
    $string_to_sign             = "GET\n{$urlparts['host']}\n{$urlparts['path']}\n$canonical";
    // Calculate our actual signature and base64 encode it
    $signature            = base64_encode(hash_hmac('sha256', $string_to_sign, $secret_key, true));

    // Finally re-build the URL with the proper string and include the Signature
    $url = "{$urlparts['scheme']}://{$urlparts['host']}{$urlparts['path']}?$canonical&Signature=".rawurlencode($signature);
    return $url;
}

$asin = $_GET["asin"];

ItemLookup($asin);
